package org.celery.modules.ticket.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.celery.modules.purchase.entity.Purchase;
import org.celery.modules.shop.entity.Shop;
import org.celery.modules.shop.service.IShopService;
import org.celery.modules.ticket.dto.TicketDTO;
import org.celery.modules.ticket.entity.SearchEntity;
import org.celery.modules.ticket.enums.payStatusEnum;
import org.celery.modules.ticket.enums.transactionStatusEnum;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.celery.modules.ticket.entity.Ticket;
import org.celery.modules.ticket.vo.TicketVO;
import org.celery.modules.ticket.wrapper.TicketWrapper;
import org.celery.modules.ticket.service.ITicketService;
import org.springblade.core.boot.ctrl.BladeController;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单表 控制器
 *
 * @author Celery
 * @since 2023-06-12
 */
@RestController
@AllArgsConstructor
@RequestMapping("celery-ticket/ticket")
@Api(value = "订单表", tags = "订单表接口")
public class TicketController extends BladeController {

	private final ITicketService ticketService;
	private final IShopService shopService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入ticket")
	public R<TicketVO> detail(Ticket ticket) {
		Ticket detail = ticketService.getOne(Condition.getQueryWrapper(ticket));
		return R.data(TicketWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 订单表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入ticket")
	public R<IPage<TicketVO>> list(Ticket ticket, Query query,
								   @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") LocalDateTime createTimeStart,
								   @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") LocalDateTime createTimeEnd,
								   @RequestParam(required = false) Boolean isClose,
								   BladeUser user) {
		QueryWrapper<Ticket> queryWrapper = Condition.getQueryWrapper(ticket);
		if(!user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) || (!user.getRoleName().contains("administrator") && !user.getRoleName().contains("s_admin") && !user.getRoleName().contains("caiwu") && !user.getRoleName().contains("fake_boss"))) {
			List<Shop> shopList = shopService.authList(user);
			if (Func.isEmpty(shopList)) {
				return R.data(new Page<>());
			}

			List<String> shopNameList = shopList.stream().map(Shop::getResourceOwner).collect(Collectors.toList());
			queryWrapper.lambda().in(Ticket::getUserName, shopNameList);
		}
		if (Func.isNotEmpty(createTimeStart) && Func.isNotEmpty(createTimeEnd)) {
			queryWrapper.lambda().between(Ticket::getCreateTime, createTimeStart, createTimeEnd);
		}
		if (Func.isNotEmpty(isClose) && isClose) {
			queryWrapper.lambda().in(Ticket::getStepStatus, new ArrayList<String>() {{
				add(transactionStatusEnum.TRANSACTION_TERMINATION.getValue());
				add(transactionStatusEnum.TRANSACTION_CANCELLATION.getValue());
			}});
		}
		queryWrapper.lambda().orderByDesc(Ticket::getTradingHours);
		IPage<Ticket> pages = ticketService.page(Condition.getPage(query), queryWrapper);
		return R.data(TicketWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 订单表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入ticket")
	public R<IPage<TicketVO>> page(TicketVO ticket, Query query) {
		IPage<TicketVO> pages = ticketService.selectTicketPage(Condition.getPage(query), ticket);
		return R.data(pages);
	}

	/**
	 * 新增 订单表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入ticket")
	public R save(@Valid @RequestBody Ticket ticket) {
		return R.status(ticketService.save(ticket));
	}

	/**
	 * 修改 订单表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入ticket")
	public R update(@Valid @RequestBody Ticket ticket) {
		return R.status(ticketService.updateById(ticket));
	}

	/**
	 * 新增或修改 订单表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入ticket")
	public R submit(@Valid @RequestBody Ticket ticket) {
		return R.status(ticketService.saveOrUpdate(ticket));
	}

	
	/**
	 * 删除 订单表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(ticketService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 获取订单列表
	 */
	@GetMapping("/custom_list")
	public R<IPage<Ticket>> getOrderList(Ticket order, Query query) {
		return R.data(ticketService.getOrderList(order, query));
	}

	/**
	 * 根据id获取订单列表
	 */
	@GetMapping("/singleOrder")
	public R<Ticket> getOrderById(@RequestParam Long orderId) {
		return R.data(ticketService.getOrderById(orderId));
	}

	/**
	 * 删除订单列表
	 */
	@GetMapping("/delete_order")
	public R<Boolean> deleteOrder(@RequestParam Long orderId) {
		return R.data(ticketService.deleteOrder(orderId));
	}

	/**
	 * 批量删除
	 */
	@GetMapping("/batchDeleteOrder")
	public R<Boolean> batchDeleteOrder(String orderIds) {
		return R.data(ticketService.batchDeleteOrder(orderIds));
	}

	/**
	 * 修改订单列表
	 */
	@PostMapping("/modify_order")
	public R<Boolean> modifyOrder(@RequestBody Ticket order) {
		return R.data(ticketService.modifyOrder(order));
	}

	/**
	 * 批量修改
	 */
	@PostMapping("/batchModifyOrder")
	public R<Boolean> batchModifyOrder(@RequestBody List<Ticket> orders) {
		return R.data(ticketService.batchModifyOrder(orders));
	}

//	@PostMapping("/add_order")
//	public R<Boolean> addOrder(@RequestBody TicketDTO order) {
//		return R.data(ticketService.addOrderInput(order));
//	}

	/**
	 * 批量新增
	 */
	@PostMapping("/batchAddOrder")
	public R<Boolean> batchAddOrder(@RequestBody List<Ticket> orders) {
		return R.data(ticketService.batchAddOrder(orders));
	}

	/**
	 * 新增订单列表
	 */
	@PostMapping("/add_order")
	public R<Boolean> addOrder(@RequestBody Ticket order) {
		return R.data(ticketService.addOrder(order));
	}

	/**
	 * 脚本或者json数据输入的实体类村粗
	 */
	@PostMapping("/add_order_input")
	public R<Boolean> addOrderInput(@RequestBody List<TicketDTO> orders) throws ParseException {
		return R.status(ticketService.addOrderInput(orders));
	}

	/**
	 * 根据编号查询订单
	 */
	@GetMapping("/get_order_likeId")
	public R<IPage<Ticket>> getOrderLikeId(Ticket order, Query query) throws ParseException {
		return R.data(ticketService.getOrderLikeId(order, query));
	}

	/**
	 * 获取订单的枚举值
	 */
	@GetMapping("/get_order_enum_list")
	public R<List<Map<String, Object>>> getOrderEnumList(){
		return R.data(payStatusEnum.toList());
	}

	/**
	 * 根据value搜索查找支付状态
	 */
	@GetMapping("/get_like_payStatus")
	public R<IPage<Ticket>> getPayStatusByLike(@RequestParam Integer payStatusValue, Query query, BladeUser user) {
		IPage<Ticket> payStatusByLike = ticketService.getPayStatusByLike(payStatusValue, query);
		if(!user.getRoleName().equals("administrator") || !user.getRoleName().equals("s_admin")) {
			payStatusByLike.setRecords(payStatusByLike.getRecords().stream().filter(item -> item.getUserName().equals(user.getUserName())).collect(Collectors.toList()));
		}
		return R.data(payStatusByLike);
	}

	/**
	 * 根据value搜索查找交易状态
	 */
	@GetMapping("/get_like_transaction_status")
	public R<IPage<Ticket>> getTransactionStatus(@RequestParam String transactionStatus, Query query) {
		return R.data(ticketService.getTransactionStatus(transactionStatus, query));
	}

	/**
	 * 根据value搜索查找退款状态
	 */
	@GetMapping("/get_like_refund_status")
	public R<IPage<Ticket>> getRefundStatus(@RequestParam String refundStatus, Query query) {
		return R.data(ticketService.getRefundStatus(refundStatus, query));
	}

	/**
	 * 根据条件进行搜索
	 */
	@PostMapping("/get_ticket_by_condition")
	public R<IPage<Ticket>> getTicketByCondition(@RequestBody SearchEntity searchEntity, Query query, BladeUser user) {
		return R.data(ticketService.getTicketByCondition(searchEntity, query, user));
	}

	/**
	 * 获取店铺的下拉接口
	 */
	@GetMapping("/get_shop_select_data")
	public R<List<HashMap<String, String>>> getShopSelectData() {
		return R.data(ticketService.getShopSelectData());
	}

	/**
	 * 通过已经付款的订单去获取对应的物流信息
	 */
	@GetMapping("/get_trade_seller_view")
	public R<Object> getTradeGetLogisticsInfosSellerViewList (@RequestParam Long orderId, @RequestParam(defaultValue = "1688") String webSite) {
		return R.data(ticketService.getTradeGetLogisticsInfosSellerViewList(orderId, webSite));
	}

	/**
	 * 返回订单信息相关的接口
	 */
	@GetMapping("/get_buyer_info")
	public R<ArrayList<HashMap<String, String>>> getTicketListForBuyerInfo (@RequestParam Long orderId) {
		return R.data(ticketService.getTicketListForBuyerInfo(orderId));
	}

	/**
	 * 物流信息相关的接口
	 */
	@GetMapping("/get_info_seller_view")
	public R<Object> getLogisticsInfosSellerView (@RequestParam Long orderId, @RequestParam String webSite) {
		return R.data(ticketService.getLogisticsInfosSellerView(orderId, webSite));
	}


	/**
	 * 返回发货的跳转地址
	 */
	@GetMapping("/get_goods_url")
	public R<Object> getSendGoodUrl (@RequestParam Long orderId) {
		return R.data(ticketService.getSendGoodUrl(orderId));
	}

	/**
	 * 设置状态为待收货章台
	 */
	@GetMapping("/change_ticket_status")
	public R<Object> changeTicketStatus (@RequestParam Long orderId) {
		return R.data(ticketService.changeTicketStatus(orderId));
	}

	/**
	 * 获取待拍单订单列表
	 */
	@GetMapping("/purchase-ticket-list")
	public R<List<Ticket>> purchaseTicketList(BladeUser user) {
		QueryWrapper<Ticket> queryWrapper = new QueryWrapper<>();
		if(!user.getRoleName().equals("administrator") || !user.getRoleName().equals("s_admin")) {
			queryWrapper.lambda().eq(Ticket::getUserName, user.getUserName());
		}
		queryWrapper.lambda().eq(Ticket::getStepStatus, "waitsellersend")
				.orderByDesc(Ticket::getCreateTime);
		return R.data(ticketService.list(queryWrapper));
	}

	/**
	 * 详情
	 */
	@GetMapping("/sync")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "同步")
	public R<TicketVO> sync(Ticket ticket) {
		Ticket detail = ticketService.getOne(Condition.getQueryWrapper(ticket));
		return R.data(TicketWrapper.build().entityVO(detail));
	}
}
